package org.zbclan.bf2.rcon.home.server;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zbclan.bf2.rcon.common.server.ServerModel;
import org.zbclan.bf2.rcon.common.server.ServerZip;
import org.zbclan.bf2.rcon.common.shared.GamePlayObject;
import org.zbclan.bf2.rcon.home.shared.SaveGamePlayObjectCommand;
import org.zbclan.bf2.rcon.home.shared.SaveGamePlayObjectResult;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class SaveGamePlayObjectHandler implements
		ActionHandler<SaveGamePlayObjectCommand, SaveGamePlayObjectResult> {

	private static final Logger logger = LoggerFactory
			.getLogger(GetLevelNameListHandler.class);

	// private final Log logger;
	private final Provider<ServletContext> servletContext;
	private final Provider<HttpServletRequest> servletRequest;
	private ServerModel serverModel;

	@Inject
	public SaveGamePlayObjectHandler(
			final Provider<ServletContext> servletContext,
			final Provider<HttpServletRequest> servletRequest,
			ServerModel serverModel) {
		// this.logger = logger;
		this.servletContext = servletContext;
		this.servletRequest = servletRequest;
		this.serverModel = serverModel;
	}

	public SaveGamePlayObjectResult execute(
			final SaveGamePlayObjectCommand cmd, final ExecutionContext context)
			throws ActionException {

		try {

			/*
			 * save
			 */
			String uri = cmd.getUri();
			GamePlayObject gpo = cmd.getGpo();

			int p = uri.indexOf("/");
			String name = uri.substring(0, p);
			String mode = uri.substring(p + 1);

			ServerZip serverZip = new ServerZip(name);
			serverZip.getGamePlayObjects().put(mode, gpo);
			serverZip.save();

			serverModel.getLevels().get(name).put(mode, gpo);

			return new SaveGamePlayObjectResult();

		} catch (Exception cause) {
			logger.error("Unable to send message", cause);
			throw new ActionException(cause);
		}

	}

	public void rollback(final SaveGamePlayObjectCommand action,
			final SaveGamePlayObjectResult result,
			final ExecutionContext context) throws ActionException {
		// Nothing to do here
	}

	public Class<SaveGamePlayObjectCommand> getActionType() {
		return SaveGamePlayObjectCommand.class;
	}
}